<template>
	<view class="container" :data-theme="theme">
		<view class="header">头部内容</view>
		<view class="content">
			<!-- 这里是可滚动的内容 -->
			<scroll-view class="scroll-view" scroll-y>
				<view class="scroll-view-inner">
					<next-tree uiMode='page' :title="getTitle" ref="nextTreeRef" :checkStrictly="checkStrictly"
						:selectParent="selectParent" :funcMode="funcMode" :treeData="treeData" @confirm="onconfirm"
						@change="handleChange">
						<template #topBar>
							<view style="background-color: #faf8fa;opacity: .8;padding: 10rpx 0 ;">
								请选择参与满减活动的品类
							</view>
						</template>
						<template #fixedBottomBar>
							<view style="display: flex;justify-content: space-between;">
								<button @click="handleBack"
									:style="{backgroundColor:'#f2f0f2',color:'black',margin: '5px',width:'50%'}"
									size="mini">上一步</button>
								<button @click="onconfirm"
									:style="{backgroundColor:bgColor,color:'#fff',margin: '5px',width:'50%'}"
									size="mini">确定品类</button>
							</view>
						</template>
					</next-tree>
				</view>
			</scroll-view>
		</view>
	</view>
</template>
<script>
	let self = null;
	import {
		setThemeColor
	} from '../../../../utils/setTheme';
	// import {
	// 	storeCategoryAllApi
	// } from "@/api/product.js"
	import {
		addActivityRegistrationApi,
		getCategoryTreeListApi,
		getNoRegistrationActivityApi
	} from "@/api/marketing.js"
	let app = getApp()
	export default {
		data() {
			return {
				bgColor: "#fff",
				theme: app.globalData.theme,
				funcMode: 'checkbox',
				selectParent: true,
				checkStrictly: true,
				activeId: '',
				generalGiftInfo: {}, // 满减信息
				categoryList: [], // 品类信息
				treeData: [],
				partGoodsList: [], //删除部分商品的数据
				categoryIds: [], // 获取到的所有品类的id
			}
		},
		onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			// 获取回显的品类信息
			this.getNoRegistrationActivity()
			// 获取需要添加的优惠信息
			if (options && options.generalGiftInfo) {
				this.generalGiftInfo = JSON.parse(options.generalGiftInfo)
			}
			// 获取需要删除的部分商品的商品  （用于切换商品范围时删除）
			if (options && options.partGoodsList) {
				this.partGoodsList = JSON.parse(options.partGoodsList)
			}
		},
		methods: {
			// 选中了多少项数据
			getTitle: function(checked) {
				return `已选：${checked.length}项`
			},
			// 回显数据 并且禁用之前所选中的数据
			echoDefault: function(selectIds) {
				this.checkedTreeData(this.treeData, selectIds)
			},
			checkedTreeData: function(treeData, selectIds) {
				// 注意 vue2当数据深嵌套时，如果没有在treeData里面初始化checked属性，那在改变数据的时候直接将checked属性赋值为true，这时候ui界面有可能不会更新，
				// 这时候建议使用this.$set去更新checked属性值，或者在初始化this.treeData的时候初始化checked属性
				(treeData || []).map(item => {
					if (selectIds.indexOf(item.id) !== -1) {
						item.checked = true
						item.disabled = true
					} else {
						item.checked = false
						item.disabled = false
					}
					if (item.children && item.children.length) {
						this.checkedTreeData(item.children, selectIds)
					}
				})
			},

			// 改变多选框内容
			handleChange(e) {
				this.categoryList = e
			},
			// 用于只需要一级列表和二级列表以及三级列表
			filterData(data) {
				return data.map(item => {
					let newItem = {
						id: item.id,
						pid: item.pid,
						name: item.name,
						icon: item.icon,
						level: item.level,
						sort: item.sort,
						isShow: item.isShow,
						children: [],
						checked: false,
						disabled: false,
					};
					if (item.childList && item.childList.length > 0) {
						newItem.children = [];
						// 处理二级数据
						item.childList
							.filter(child => child.level === 2)
							.forEach(child => {
								let secondLevelItem = {
									id: child.id,
									pid: child.pid,
									name: child.name,
									icon: child.icon,
									level: child.level,
									sort: child.sort,
									isShow: child.isShow,
									children: [],
									checked: false,
									disabled: false,
								}
								// 处理三级数据
								if (child.childList && child.childList.length > 0) {
									secondLevelItem.children = this.filterData(child.childList.filter(
										grandchild => grandchild.level === 3));
								}

								newItem.children.push(secondLevelItem);
							});
					}

					return newItem;
				});
			},
			// 遍历树形结构  取出每一级的id
			extractIds(tree, result = []) {
				tree.forEach(node => {
					result.push(node.id); // 将当前节点的 id 加入结果数组
					if (node.childList.length > 0) {
						this.extractIds(node.childList, result); // 递归处理子节点
					}
				});
				return result;
			},

			// 返回上一步
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			// 确认提交品类事件
			onconfirm: function(list) {
				let that = this
				if (!this.categoryList.length) return uni.showToast({
					title: '请至少选择一个品类',
					icon: 'none',
					duration: 2000
				})

				uni.showModal({
					title: '提示',
					content: '确定选择该品类吗？',
					success({
						confirm,
						cancel
					}) {
						if (confirm) {
							that.addActivityRegistration()
						} else {
							uni.showToast({
								title: '已取消',
								duration: 2000,
								icon: "none"
							})
						}
					}
				})
			},
			// -----------------------------------api-------------------
			// 添加满减信息
			async addActivityRegistration() {
				let that = this
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				try {
					// 查找数据中选中的三级分类数据
					let filterCategoryList = this.categoryList.filter(item => item.level == 3)
					this.generalGiftInfo.addEnrolledActivityProductDTOList = filterCategoryList.map(item => {
						return {
							businessSign: 1,
							productCategoryId: item.id
						}
					})
					this.generalGiftInfo.addEnrolledActivityProductDTOList.push(...this.partGoodsList)
					let data = {
						activityCategory: this.generalGiftInfo.activityCategory,
						activityScopeList: this.generalGiftInfo.activityScopeList,
						activitySubsidyList: this.generalGiftInfo.activitySubsidyList,
						activityTimeList: this.generalGiftInfo.activityTimeList,
						customerDailyLimit: this.generalGiftInfo.customerDailyLimit,
						totalOrderLimit: this.generalGiftInfo.totalOrderLimit,
						productScope: this.generalGiftInfo.productScope,
						addEnrolledActivityProductDTOList: this.generalGiftInfo.addEnrolledActivityProductDTOList,
					}
					let res = await addActivityRegistrationApi(data)
					if (res.code == 200) {
						uni.showModal({
							title: '提示',
							content: '创建成功点击确认跳转到店铺满减首页',
							showCancel: false,
							success: (res) => {
								if (res.confirm == true) {
									uni.redirectTo({
										url: '/pages/marketing/fullDiscountList/index',
									});
								}
							}
						})
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					uni.showToast({
						title: e,
						icon: 'none',
						duration: 1500
					})
					//TODO handle the exception
					console.log("e", e)
				}
				uni.hideLoading()
			},
			// 获取三级分类数据
			async storeCategoryAll() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				try {
					let res = await getCategoryTreeListApi()
					if (res.code == 200) {
						// 过滤出 level = 1 和 level = 2 level = 3 的数据
						this.treeData = this.filterData(res.data);
						// 回显品类信息  默认选中状态
						this.echoDefault(this.categoryIds)

					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					uni.showToast({
						title: e,
						icon: 'none',
						duration: 1500
					})
					console.log("e", e)
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			// 获取活动商品信息
			async getNoRegistrationActivity() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				try {
					let res = await getNoRegistrationActivityApi(7)
					if (res.code == 200) {
						// 判断有没有选中的品类 获取获取到的品类信息  取出所有的分类中的id
						if (res.data.proCategoryCacheVoList && res.data.proCategoryCacheVoList.length) {
							this.categoryIds = this.extractIds(res.data.proCategoryCacheVoList);
						}
						// 获取品类分类数据
						this.storeCategoryAll()
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 2000
						});
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: e,
						duration: 2000,
						icon: 'none'
					})
				}
				uni.hideLoading()
			},
		},

		created() {
			self = this
		},

	}
</script>
<style lang="scss">
	.line-block {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;

		.img {
			width: 40rpx;
			height: 40rpx;
			border-radius: 10rpx;
			margin: 0 20rpx;
		}
	}
</style>
<style lang="scss">
	page {
		height: 100%;


	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		height: 100px;
		background-color: lightblue;
	}

	.content {
		flex: 1;
		overflow: hidden;
	}

	.scroll-view {
		height: 100%;
	}

	.scroll-view-inner {
		padding: 40rpx;
		background-color: #eee;
	}
</style>